package com.example.forum.service.impl;

import com.example.forum.common.AppResult;
import com.example.forum.common.ResultCode;
import com.example.forum.dao.UserMapper;
import com.example.forum.exception.ApplicationException;
import com.example.forum.model.Board;
import com.example.forum.model.User;
import com.example.forum.service.IUserService;
import com.example.forum.utils.IdNotNullUtil;
import com.example.forum.utils.MD5Util;
import com.example.forum.utils.UUIDUtil;
import jakarta.annotation.Resource;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

/**
 * 功能描述:
 *
 * @author Lenovo
 * @date 2024/12/12
 */
@Slf4j
@Service
public class UserServiceImpl implements IUserService {
    @Resource
    private UserMapper userMapper;

    /**
     * 创建新用户
     *
     * @param user 新用户信息
     */
    @Override
    public void createNormalUser(User user) {
        //非空校验
        if (user == null || !StringUtils.hasLength(user.getUsername())
                || !StringUtils.hasLength(user.getNickname())
                || !StringUtils.hasLength(user.getPassword())
                || !StringUtils.hasLength(user.getSalt())) {
            log.error(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //判断用户是否存在
        User exitsUser = userMapper.selectByUsername(user.getUsername());
        if (exitsUser != null) {
            log.info(ResultCode.FAILED_USER_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_EXISTS));
        }
        //新增用户，设置默认值
        user.setGender((byte) 2);
        user.setArticleCount(0);
        user.setIsAdmin((byte) 0);
        user.setState((byte) 0);
        user.setDeleteState((byte) 0);
        Date date = new Date();
        user.setCreateTime(date);
        user.setUpdateTime(date);
        //新增用户（动态插入）
        int row = userMapper.insertSelective(user);
        if (row != 1) {
            log.info(ResultCode.FAILED_CREATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }
        log.info(ResultCode.SUCCESS.toString());
    }

    /**
     * 根据用户名查询用户信息
     *
     * @param username 用户名
     * @return 用户信息
     */
    @Override
    public User selectByUsername(String username) {
        if (!StringUtils.hasLength(username)) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        return userMapper.selectByUsername(username);
    }

    /**
     * 登录
     *
     * @param username 用户名
     * @param password 密码
     * @return 用户信息
     */
    @Override
    public User login(String username, String password) {
        //非空校验
        if (!StringUtils.hasLength(username) || !StringUtils.hasLength(password)) {
            log.warn(ResultCode.FAILED_LOGIN.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }
        User user = selectByUsername(username);
        if (user == null) {
            log.warn(ResultCode.FAILED_LOGIN.toString() + ", username: " + username);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }
        //校验密码
        String salt = user.getSalt();
        String userPassword = user.getPassword();
        if (!MD5Util.verify(salt, password, userPassword)) {
            log.warn(ResultCode.FAILED_LOGIN.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }
        //校验成功
        log.info(ResultCode.SUCCESS.toString());
        return user;
    }

    @Override
    public User selectById(Long id) {
        //非空校验
        if (id == null) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //获取对象
        return userMapper.selectByPrimaryKey(id);
    }

    @Override
    public void addOneArticleCountById(Long id) {
        //id输入有误
        IdNotNullUtil.idNotNullUtil(id);
        //查询对应用户
        User user = userMapper.selectByPrimaryKey(id);
        if (user == null) {
            log.warn(ResultCode.ERROR_IS_NULL.toString() + "board id : " + id);
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NULL));
        }
        //重新创建一个User对象作为更新对象传入动态sql（保证数据安全性和完整性）
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setUpdateTime(new Date());
        updateUser.setArticleCount(user.getArticleCount() + 1);
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        //判断受影响的行数
        if (row != 1) {
            log.warn(ResultCode.FAILED.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
    }

    @Override
    public void subOneArticleCountById(Long id) {
        //id输入有误
        IdNotNullUtil.idNotNullUtil(id);
        //查询对应用户
        User user = userMapper.selectByPrimaryKey(id);
        if (user == null) {
            log.warn(ResultCode.ERROR_IS_NULL.toString() + "user id : " + id);
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NULL));
        }
        //重新创建一个User对象作为更新对象传入动态sql（保证数据安全性和完整性）
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setUpdateTime(new Date());
        updateUser.setArticleCount(user.getArticleCount() - 1);
        if (updateUser.getArticleCount() < 0) {
            updateUser.setArticleCount(0);
        }
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        //判断受影响的行数
        if (row != 1) {
            log.warn(ResultCode.FAILED.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
    }

    @Override
    public void modifyInfo(User user) {
        //非空校验
        if (user == null || user.getId() == null || user.getId() <= 0) {
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //校验用户是否存在
        User existsUser = userMapper.selectByPrimaryKey(user.getId());
        if (existsUser == null) {
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        //定义标志位，用来表示校验是否通过
        boolean checkAttribute = false;
        //构建更新对象
        User updateUser = new User();
        updateUser.setId(existsUser.getId());

        //用户名
        if (StringUtils.hasLength(user.getUsername()) &&
                !user.getUsername().equals(existsUser.getUsername())) {
            User checkUser = userMapper.selectByUsername(user.getUsername());
            //用户已存在
            if (checkUser != null) {
                throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_EXISTS));
            }
            updateUser.setUsername(user.getUsername());
            //更新标志位
            checkAttribute = true;
        }
        //昵称
        if (StringUtils.hasLength(user.getNickname()) &&
                !user.getNickname().equals(existsUser.getNickname())) {
            updateUser.setNickname(user.getNickname());
            checkAttribute = true;
        }
        //性别
        if (user.getGender() != null &&
                !user.getGender().equals(existsUser.getGender())) {
            updateUser.setGender(user.getGender());
            //合法性校验
            if (user.getGender() > 2 || user.getGender() < 0) {
                updateUser.setGender((byte) 2);
            }
            checkAttribute = true;
        }
        //email
        if (StringUtils.hasLength(user.getEmail()) &&
                !user.getEmail().equals(existsUser.getEmail())) {
            updateUser.setEmail(user.getEmail());
            checkAttribute = true;
        }
        //phone
        if (StringUtils.hasLength(user.getPhoneNum()) &&
                !user.getPhoneNum().equals(existsUser.getPhoneNum())) {
            updateUser.setPhoneNum(user.getPhoneNum());
            checkAttribute = true;
        }
        //个人简介
        if (StringUtils.hasLength(user.getRemark()) &&
                !user.getRemark().equals(existsUser.getRemark())) {
            updateUser.setRemark(user.getRemark());
            checkAttribute = true;
        }
        //头像
        if (StringUtils.hasLength(user.getAvatarUrl())) {
            updateUser.setAvatarUrl(user.getAvatarUrl());
            checkAttribute = true;
        }
        if (!checkAttribute) {
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if (row != 1) {
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
    }

    @Override
    public void modifyPassword(Long id, String newPassword, String oldPassword) {
        //非空校验
        if (id == null || id <= 0 ||
                !StringUtils.hasLength(newPassword) || !StringUtils.hasLength(oldPassword)) {
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //校验用户是否存在
        User user = userMapper.selectByPrimaryKey(id);
        if (user == null || user.getDeleteState() == 1) {
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        //校验原密码
        String oldEncryptPassword = MD5Util.encrypt(oldPassword, user.getSalt());
        if (!oldEncryptPassword.equalsIgnoreCase(user.getPassword())) {
            log.info(ResultCode.FAILED.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_SAME));
        }
        //修改密码
        String salt = UUIDUtil.getSalt(); //生成新盐值
        String encryptPassword = MD5Util.encrypt(newPassword, salt);

        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setSalt(salt);
        updateUser.setPassword(encryptPassword);
        updateUser.setUpdateTime(new Date());

        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if (row != 1) {
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
    }

    @Override
    public void modifyPassword(Long id, String newPassword) {
        //非空校验
        if (id == null || id <= 0 || !StringUtils.hasLength(newPassword) ) {
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //校验用户是否存在
        User user = userMapper.selectByPrimaryKey(id);
        if (user == null || user.getDeleteState() == 1) {
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        //修改密码
        String salt = UUIDUtil.getSalt(); //生成新盐值
        String encryptPassword = MD5Util.encrypt(newPassword, salt);

        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setSalt(salt);
        updateUser.setPassword(encryptPassword);
        updateUser.setUpdateTime(new Date());

        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if (row != 1) {
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
    }

    @Override
    public User selectByEmail(String email) {
        if (!StringUtils.hasLength(email)) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        return userMapper.selectByEmail(email);
    }
}
